#include "bbs.h"

char *curuserid;

struct libstruct {
    char id[STRLEN];
    char nick[NAMELEN];
    unsigned int data;
} *lib;
int total=0,flag=0;
int tm_mon, tm_mday, cur = 0; //for birthday

int show()
{
    int i;
    switch (flag) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
	    printf("<?xml version=\"1.0\" encoding=\"GBK\"?>\n");
	    printf("<statguys>\n");
            break;
    }
    for (i=0; i<total; i++) {
        if (flag==2) {
	    printf("<statguy>\n");
	    printf("<num>%d</num>\n",i+1);
	    printf("<userid>%s</userid>\n",lib[i].id);
	    printf("<time>%d</time>\n",lib[i].data);
	    printf("</statguy>\n");
        } else {
	    printf("<statguy>\n");
	    printf("<num>%d</num>\n",i+1);
	    printf("<userid>%s</userid>\n",lib[i].id);
	    printf("<stat>%d</stat>\n",lib[i].data);
	    printf("</statguy>\n");
	}
	    
    }
	printf("</statguys>\n");
    return 0;
}

int statit(struct userec *user, void *arg)
{
    int d,k,i,j;
    time_t temp;
    if (!strcmp(user->userid,"guest")) return 0;
    if (user->userid[0]<'A'||user->userid[0]>'z') return 0;
    switch (flag) {
        case 0:
            d = user->numlogins;
            break;
        case 1:
            d = user->numposts;
            break;
        case 2:
            d = user->stay;
            break;
        case 3:
            d = countexp(user);
            break;
        case 4:
            d = countperf(user);
            break;
        default:
            return 1;
    }
    /* reg time bug, 3 line add by xbwbbs-latitude 2008.5.6 */
    time(&temp);
    k = temp - user->firstlogin;
    if((user->stay <= 0) || (user->stay/k >= 1)) return 1;

    for (i=0; i<total; i++)
        if (lib[i].data<d) {
            for (j=total-1;j>i;j--)
                memcpy(&lib[j],&lib[j-1],sizeof(struct libstruct));
            strcpy(lib[i].id, user->userid);
            strcpy(lib[i].nick, user->username);
            lib[i].data = d;
            break;
        }
    return 1;
}

int main(int argc,char **argv)
{
    if (argc<=2) {
        printf("usage: statguy login|post|stay|exp|pref <total>\n");
        return -1;
    }
    if (!strcmp(argv[1], "login")) flag = 0;
    if (!strcmp(argv[1], "post")) flag = 1;
    if (!strcmp(argv[1], "stay")) flag = 2;
    if (!strcmp(argv[1], "exp")) flag = 3;
    if (!strcmp(argv[1], "pref")) flag = 4;
    total=atoi(argv[2]);
    if (!total) {
        printf("error: <total> must be an integer and greater than zero!\n");
        return -2;
    }
    chdir(BBSHOME);
    resolve_ucache();
    resolve_boards();
    lib = malloc(sizeof(struct libstruct)*total);
    memset(lib, 0, sizeof(struct libstruct)*total);
    apply_users(statit, NULL);

    show();

    return 0;
}
